package com.atguigu.ting.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.annotation.NotSink;
import com.atguigu.ting.realtime.bean.TableProcess;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.sink.PhoenixSink;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.connector.sink2.Sink;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.shaded.guava30.com.google.common.base.CaseFormat;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @Author lzc
 * @Date 2023/3/11 09:02
 */
public class FlinkSinkUtil {
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getPhoenixSink() {
        return new PhoenixSink();
    }
    
    public static SinkFunction<String> getKafkaSink(String topic) {
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", Constant.KAFKA_SERVERS);
        props.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");
        
        
        return new FlinkKafkaProducer<String>(
            "default",
            new KafkaSerializationSchema<String>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(String element,
                                                                @Nullable Long timestamp) {
                    byte[] content = null;
                    if (element != null) {
                        content = element.getBytes(StandardCharsets.UTF_8);
                        return new ProducerRecord<>(topic, content);
                    }
                    return new ProducerRecord<>("default", null); // 防止向 topic 种写入 null
                }
                
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getKafkaSink() {
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", Constant.KAFKA_SERVERS);
        props.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");
        
        return new FlinkKafkaProducer<Tuple2<JSONObject, TableProcess>>(
            "default",
            new KafkaSerializationSchema<Tuple2<JSONObject, TableProcess>>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(Tuple2<JSONObject, TableProcess> t,
                                                                @Nullable Long timestamp) {
                    byte[] data = t.f0.toJSONString().getBytes(StandardCharsets.UTF_8);
                    String topic = t.f1.getSinkTable();
                    return new ProducerRecord<>(topic, data);
                }
                
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
        
    }
    
    public static <T> SinkFunction<T> getClickHouseSink(String tableName,
                                                        Class<T> tClass) {
        String columns = Arrays
            .stream(tClass.getDeclaredFields())
            .filter(field -> {
                NotSink notSink = field.getAnnotation(NotSink.class);
                // 如果没有就返回 null
                return notSink == null;
            })
            .map(f -> {
                return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, f.getName());
            })
            .collect(Collectors.joining(","));
        // insert into t(stt,edt,keyword,keyword_count,ts)values(?,?,?,?,?)
        StringBuilder sql = new StringBuilder();
        sql
            .append("insert into ")
            .append(tableName)
            .append("(")
            .append(columns)
            .append(")values(")
            .append(columns.replaceAll("[^,]+", "?"))
            .append(")");
        
        System.out.println("插入语句: " + sql);
        
        return JdbcSink.sink(
            sql.toString(),
            new JdbcStatementBuilder<T>() {
                @Override
                public void accept(PreparedStatement ps,
                                   T t) throws SQLException {
                    try {
                        // 数据在对象中: t
                        Field[] fields = tClass.getDeclaredFields();
                        
                        for (int i = 0, position = 1; i < fields.length; i++) {
                            Field field = fields[i];
                            if (field.getAnnotation(NotSink.class) == null) {
                                field.setAccessible(true);
                                
                                Object v = field.get(t);
                                ps.setObject(position++, v);
                            }
                            
                        }
                        
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            },
            new JdbcExecutionOptions.Builder()
                .withBatchSize(1000)// 批次大小
                .withBatchIntervalMs(3000)  // 3000ms刷新一次
                .withMaxRetries(3) // 重试次数
                .build(),
            new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                .withDriverName(Constant.CLICKHOUSE_DRIVER)
                .withUrl(Constant.CLICKHOUSE_URL)
                .withUsername("default")  // 如果没有设置密码, 则用户名和密码都不要输入
                .withPassword("aaaaaa")
                .build()
        );
    }
    
    public static Sink<String> getKafkaSinkV2(String topic) {
        return KafkaSink.<String>builder()
            .setBootstrapServers(Constant.KAFKA_SERVERS)
            .setRecordSerializer(KafkaRecordSerializationSchema.<String>builder()
                                     .setTopic(topic)
                                     .setValueSerializationSchema(new SimpleStringSchema())
                                     .build())
            .setTransactionalIdPrefix(topic+"-")
            .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
            .setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "")
            .build();
    }
    
}
